//
//  QSScanCodeView.swift
//  TestSwift
//
//  Created by Song on 2018/4/30.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit
import AVFoundation

class QSScanCodeView: UIView {
    /** 配置项 */
    // 扫描框的宽
    private var qs_scanContentViewWidth: CGFloat = 240
    // 扫描框的高
    private var qs_scanContentViewHeight: CGFloat = 240
    // 扫描框的圆角
    private var qs_scanContentViewCorner: CGFloat = 5
    // 扫描框的Y值
    private var qs_scanContentTop: CGFloat = 200
    // 扫描的横线图片
    private var qs_scanLineImgName: String = "friend_bubble_Transfer_me"
    // 扫描图片的高度
    private let qs_scanLineHieght: CGFloat = 12
    // 扫描一屏所需的时间(秒)
    private let qs_timeInterval: CGFloat = 3
    // 扫描框外部的view的透明度
    private let qs_outsideScanViewColor: UIColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
    // 四个直角的图片名
    private let qs_cornerImgName: String = "background_transfer_scanning"
    // 手电筒的图片
    private let qs_flashlightBtnNormalImgName: String = "icon_transfer_flashlight"
    private let qs_flashlightBtnSelectedImgName: String = "icon_transfer_flashlight"
    
    /**
     *  子控件
     */
    // 扫描的横线视图
    private var qs_scanLine: UIImageView!
    private var qs_scanContentView: UIView!
    var qs_flashlightBtn: UIButton?
    
    // 定时器
    private var qs_timer: Timer?
    // 向上或向下扫描，true: 下；false: 上
    private var upOrDownScan = true
    
    /**
     *  初始化
     */
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 创建扫描边框
        self.qs_setScanBorder()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Private Methods
    /**
     *  创建扫描边框
     */
    private func qs_setScanBorder() {
        // 扫描内容的创建
        qs_scanContentView = UIView.init()
        self.addSubview(qs_scanContentView)
        
        qs_scanContentView.snp.makeConstraints { (make) in
            make.top.equalTo(self.qs_scanContentTop)
            make.centerX.equalTo(self)
            make.width.equalTo(self.qs_scanContentViewWidth)
            make.height.equalTo(self.qs_scanContentViewHeight)
        }
        
        qs_scanContentView.layer.borderColor = UIColor.white.withAlphaComponent(0.6).cgColor
        qs_scanContentView.layer.borderWidth = 0.7
        qs_scanContentView.layer.cornerRadius = 5.0
        qs_scanContentView.layer.masksToBounds = true
        qs_scanContentView.backgroundColor = UIColor.clear
        
        // 扫描框外部的View
        self.qs_cutScanContentView()
        
        // 手电筒按钮
        qs_flashlightBtn = UIButton.init()
        self.addSubview(qs_flashlightBtn!)
        
        qs_flashlightBtn?.snp.makeConstraints { (make) in
            make.centerX.equalTo(qs_scanContentView)
            make.bottom.equalTo(qs_scanContentView.snp.bottom).offset(-20.0)
        }
        
        qs_flashlightBtn?.setImage(UIImage.init(named: qs_flashlightBtnNormalImgName), for: UIControlState.normal)
        qs_flashlightBtn?.setImage(UIImage.init(named: qs_flashlightBtnSelectedImgName), for: UIControlState.selected)
        qs_flashlightBtn?.addTarget(self, action: #selector(self.qs_clickFlashlightBtn(btn:)), for: UIControlEvents.touchUpInside)
        
        // tipLab
        let tipLab = UILabel.init()
        self.addSubview(tipLab)
        
        tipLab.snp.makeConstraints { (make) in
            make.left.equalTo(15.0)
            make.right.equalTo(-15.0)
            make.top.equalTo((qs_flashlightBtn?.snp.bottom)!).offset(50.0)
        }
        
        tipLab.textAlignment = .center
        tipLab.font = UIFont.systemFont(ofSize: 15.0)
        tipLab.textColor = UIColor.white
        tipLab.text = "将二维码放入框内即可自动扫描"
        
        // 扫描区域的四角图片
        let cornerImgView = UIImageView.init()
        self.addSubview(cornerImgView)
        
        cornerImgView.snp.makeConstraints { (make) in
            make.top.left.equalTo(qs_scanContentView).offset(-2.0)
            make.right.bottom.equalTo(qs_scanContentView).offset(2.0)
        }
        
        cornerImgView.image = UIImage.init(named: qs_cornerImgName)
        
        // 扫描动画添加
        let scanLine = UIImageView.init()
        self.addSubview(scanLine)
        self.qs_scanLine = scanLine
        scanLine.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(qs_scanContentView)
            make.height.equalTo(self.qs_scanLineHieght)
        }
        
        scanLine.image = UIImage.init(named: self.qs_scanLineImgName)
        
        // 添加定时器
        self.qs_timer = Timer.qs_init(timeInterval: TimeInterval(0.01)) { (timer) in
            self.qs_timeOut()
        }
    }
    
    /**
     *  点击手电筒按钮
     */
    @objc private func qs_clickFlashlightBtn(btn: UIButton) {
        guard let device = AVCaptureDevice.default(for: AVMediaType.video) else {
            return
        }
        
        if device.hasTorch && device.hasFlash {
            if let _ = try? device.lockForConfiguration() {
                if btn.isSelected {
                    device.torchMode = .off
                    device.flashMode = .off
                } else {
                    device.torchMode = .on
                    device.flashMode = .on
                }
                
                btn.isSelected = !btn.isSelected
                device.unlockForConfiguration()
            }
        } else {
            // 初始化失败
            btn.isHidden = true
        }
    }
    
    /**
     *  定时器方法
     */
    private func qs_timeOut() {
        guard let timer = self.qs_timer else { return }
        
        // 暂停定时器
        timer.qs_suspendTimer()
        
        self.qs_scanLine.superview?.layoutIfNeeded()
        UIView.animate(withDuration: TimeInterval(self.qs_timeInterval), animations: {
            self.qs_scanLine.snp.updateConstraints({ (make) in
                if self.upOrDownScan {
                    make.top.equalTo(self.qs_scanContentView).offset(self.qs_scanContentViewHeight - self.qs_scanLineHieght)
                } else {
                    make.top.equalTo(self.qs_scanContentView).offset(0.0)
                }
            })
            self.qs_scanLine.superview?.layoutIfNeeded()
        }) { (complete) in
            if complete {
                self.upOrDownScan = !self.upOrDownScan
                timer.qs_fireTimer()
            }
        }
    }
    
    /**
     *  裁剪出扫描框的透明部分
     */
    private func qs_cutScanContentView() {
        // 中间透明四周不透明的view
        let bgView = UIView.init()
        self.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        
        bgView.backgroundColor = self.qs_outsideScanViewColor
        
        bgView.superview?.layoutIfNeeded()
        let path = UIBezierPath.init(rect: bgView.frame)
        let path1 = UIBezierPath.init(roundedRect: self.qs_scanContentView.frame, cornerRadius: self.qs_scanContentViewCorner)
        path.append(path1.reversing())
        
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.path = path.cgPath
        
        bgView.layer.mask = shapeLayer
    }
    
    deinit {
        // 删除定时器
        self.qs_timer?.qs_invalidateTimer()
    }
}
